package com.yang.job.domain.event.handler;

import com.google.common.eventbus.Subscribe;
import com.yang.job.domain.enums.JobExecuteStrategyEnum;
import com.yang.job.domain.event.SubmitJobPostEvent;
import com.yang.job.domain.gateway.repository.IJobModelRepository;
import com.yang.job.domain.model.YangJobModel;
import com.yang.job.infra.event.IEventHandler;
import com.yang.job.infra.job.request.YangJobSubmitParam;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


@Component
public class SubmitJobPostEventHandler implements IEventHandler<SubmitJobPostEvent> {
    @Resource
    private IJobModelRepository jobModelRepository;

    @Override
    @Subscribe
    public void execute(SubmitJobPostEvent event) {
        YangJobSubmitParam yangJobSubmitParam = event.getData();
        JobExecuteStrategyEnum jobExecuteStrategy = yangJobSubmitParam.getJobExecuteStrategy();
        if (jobExecuteStrategy == JobExecuteStrategyEnum.IMMEDIATE_EXECUTE || jobExecuteStrategy == JobExecuteStrategyEnum.ONCE) {
            // 对于立即执行的任务，执行完毕后，要关闭任务
            YangJobModel yangJobModel = jobModelRepository.getYangJobModelById(yangJobSubmitParam.getJobId());
            if (!yangJobModel.isOpen()) {
                return;
            }
            yangJobModel.setOpen(0);
            jobModelRepository.updateYangJobModel(yangJobModel);
        }
    }
}


